﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Adex;
using System.Data;
using System.Data.SqlClient;
using System.Transactions;
using MediaMonitor.Common;
using System.Collections;

namespace MediaMonitor.Admin
{

    public partial class Company_Mgmt_AddEdit : Adex.BasePage
    {
       
        String[] StrSplitted = null;
        String[] StrNewSplitted = null;
        protected void Page_Load(object sender, EventArgs e)
        {


            if (!IsPostBack)
            {
                Utility.AddDateControlToPage(this.Page);
                //set dtSelCats
                DataTable dtSelCats = new DataTable();
                dtSelCats.Columns.Add("CategoryCode", Type.GetType("System.String"));
                dtSelCats.Columns.Add("CategoryName", Type.GetType("System.String"));
                dtSelCats.Columns.Add("CategoryID", Type.GetType("System.String"));
                dtSelCats.Clear();
                Session["CurDtSalCats_CompMgmtPage"] = dtSelCats;
                
                //set dtNewSelCats
                DataTable dtNewSelCats = new DataTable();
                dtNewSelCats.Columns.Add("CategoryCode", Type.GetType("System.String"));
                dtNewSelCats.Columns.Add("CategoryName", Type.GetType("System.String"));
                dtNewSelCats.Columns.Add("CategoryID", Type.GetType("System.String"));
                dtNewSelCats.Clear();

                Session["CurDtSalNewCats_CompMgmtPage"] = dtNewSelCats; //Commercial Categories

                Session["CalSelValues"] = "";
                Session["CalNewSelValues"] = "";
                //fill module checkbox list
                FillModules();

                //fill price per second keys
                FillPriceKeys();

                //fill News Templates
                FillNewsTemplates();

                string cid = Utility.GetRequestedVal("cid", "0");

                if (cid == "0")
                {
                    hdnFormMode.Value = "add";
                    hdnCurPkId.Value = "0";
                }
                else
                {
                    hdnFormMode.Value = "edit";
                    hdnCurPkId.Value = cid;
                    DoEdit();
                }

            }

            lblMsg.Text = lblMsg_top.Text = "";
            SetCrudButtons();

        }

        private void FillNewsTemplates()
        {
            SqlDataReader rd = (SqlDataReader)NewsTemplate.Query().ExecuteReader();
            lstNewsTemplate.DataSource = rd;
            lstNewsTemplate.DataBind();
            rd.Close();
             
            lstNewsTemplate.Items.Insert(0, new ListItem("- SELECT -", ""));
        }

        private void FillPriceKeys()
        {
            DataTable dt = AppSetting.Query().SetSelectList("KeyName, Value, AppSettingID").WHERE("MasterKey", "PricePerSecond").ORDER_BY("Value").ExecuteDataSet().Tables[0];
            lstPriceKey.DataSource = dt;
            lstPriceKey.DataBind();
            lstPriceKey.Items.Insert(0, new ListItem("- select -", "0"));
        }


        private void FillModules()
        {
            ModuleXCollection colMod = new ModuleXCollection();
            colMod.Load().OrderByAsc("ModuleName");
            lstModules.DataSource = colMod;
            lstModules.DataBind();
        }


      

        protected void radGridCats_ItemDataBound(object sender, Telerik.Web.UI.GridItemEventArgs e)
        {
            if (e.Item is Telerik.Web.UI.GridDataItem)// to access a row 
            {
                Telerik.Web.UI.GridDataItem item = (Telerik.Web.UI.GridDataItem)e.Item;

                if (StrSplitted != null)
                {
                    foreach (String word in StrSplitted)
                    {
                        if (word == item.GetDataKeyValue("CategoryID").ToString())
                        {
                            item.Selected = true;
                        }
                    }
                }
          }
        }


        protected void radGridCats_NeedDataSource(object source, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
            DataTable dt = VCategory.Query().ORDER_BY("CategoryName").ExecuteDataSet().Tables[0];
            DataView dataView = dt.DefaultView;
            DataTable tbl = null;
            tbl=dataView.ToTable(true, "CategoryCode", "CategoryName", "CategoryID", "SectorName");
            DataColumn[] keyColumns = new DataColumn[] { tbl.Columns["CategoryCode"], tbl.Columns["CategoryName"], tbl.Columns["SectorName"] };
            //remove the duplicates
            tbl = RemoveDuplicates(tbl, keyColumns);

            radGridCats.DataSource = tbl;

            if (!String.IsNullOrEmpty(Session["CalSelValues"].ToString()))
            {
                StrSplitted = Session["CalSelValues"].ToString().Split(',');
            }

        }


        protected void radGridNewCats_NeedDataSource(object source, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {

            ArrayList lst = new ArrayList();
            lst.Clear();
            lst.Add("TV");
            lst.Add("PR");
            lst.Add("RD");

            DataTable dt = VCategory.Query().WHERE("MediaType").IN("MediaType", lst).AND("TV", 1).OR("PR", 1).OR("RD", 1).ORDER_BY("CategoryName").ExecuteDataSet().Tables[0];
            DataView dataView = dt.DefaultView;
            dataView.RowFilter = "MediaType <> 'TVCR'";

            DataTable tbl = null;
            tbl=  dataView.ToTable(true, "CategoryCode", "CategoryName", "CategoryID", "SectorName");
            DataColumn[] keyColumns = new DataColumn[] { tbl.Columns["CategoryCode"], tbl.Columns["CategoryName"], tbl.Columns["SectorName"] };
            //remove the duplicates
             tbl=  RemoveDuplicates(tbl, keyColumns);
            radGridNewCats.DataSource = tbl;
            
            if (!String.IsNullOrEmpty(Session["CalNewSelValues"].ToString()))
            {
                StrNewSplitted = Session["CalNewSelValues"].ToString().Split(',');
            }

        }

        private DataTable  RemoveDuplicates(DataTable tbl, DataColumn[] keyColumns)
         {

            int rowNdx = 0;

            while (rowNdx < tbl.Rows.Count)
            {

                DataRow[] dups = FindDups(tbl, rowNdx, keyColumns);

                if (dups.Length > 0)
                {

                    foreach (DataRow dup in dups)
                    {

                        tbl.Rows.Remove(dup);

                    }

                }

                else
                {

                    rowNdx++;

                }

            }
            return tbl;
        }

        private static DataRow[] FindDups(DataTable tbl, int sourceNdx, DataColumn[] keyColumns)
        {

            ArrayList retVal = new ArrayList();
            DataRow sourceRow = tbl.Rows[sourceNdx];

            for (int i = sourceNdx + 1; i < tbl.Rows.Count; i++)
            {

                DataRow targetRow = tbl.Rows[i];

                if (IsDup(sourceRow, targetRow, keyColumns))
                {

                    retVal.Add(targetRow);

                }

            }

            return (DataRow[])retVal.ToArray(typeof(DataRow));

        }
        private static bool IsDup(DataRow sourceRow, DataRow targetRow, DataColumn[] keyColumns)
           {

            bool retVal = true;

            foreach (DataColumn column in keyColumns)
            {

                retVal = retVal && sourceRow[column].Equals(targetRow[column]);

                if (!retVal) break;

            }

            return retVal;

        }
        
        protected void radGridNewCats_ItemDataBound(object sender, Telerik.Web.UI.GridItemEventArgs e)
        {
            if (e.Item is Telerik.Web.UI.GridDataItem)// to access a row 
            {
                Telerik.Web.UI.GridDataItem item = (Telerik.Web.UI.GridDataItem)e.Item;

                if (StrNewSplitted != null)
                {
                    foreach (String newword in StrNewSplitted)
                    {
                        if (newword == item.GetDataKeyValue("CategoryID").ToString())
                        {
                            item.Selected = true;
                        }
                    }
                }
            }
        } 

        


        protected void DoEdit()
        {


            Adex.Company comp = new Adex.Company(hdnCurPkId.Value);
            this.tbCompanyName.Text = comp.CompanyName;
            this.imgLog.ImageUrl = "../images/companies/tn/" + comp.Logo;
            this.tbValidFrom.Text = Utility.ToDateTime(comp.ValidFrom).ToShortDateString();
            this.tbValidTo.Text = Utility.ToDateTime(comp.ValidTo).ToShortDateString();
            this.tbCredits.Text = Utility.ToInt(comp.Credits).ToString();
            Utility.SelectListItemByText(lstPriceKey, comp.PricePerSecond.ToString());

            Utility.SelectListItem(lstNewsTemplate, comp.NewsTemplateID.ToString());

            chkUnlimitedCredits.Checked = comp.UnlimitedCredits;
            tbCredits.Enabled = !chkUnlimitedCredits.Checked;
            tbCredits.Text = chkUnlimitedCredits.Checked ? "9999999" : comp.Credits.ToString();

            this.chkAcitve.Checked = comp.Active;
            this.chkUnlimitedCategories.Checked = comp.UnlimitedCategories;
            radGridCats.Visible = !comp.UnlimitedCategories;

            this.chkUnlimitedNewCategories.Checked = comp.UnlimitedCommercialCategories; // Commercial
            radGridNewCats.Visible = !comp.UnlimitedCommercialCategories; //Commercial
           

            //select compcats
            CompanyCategoryCollection colCompCat = comp.CompanyCategoryRecords();
            DataTable dtSelCats = (DataTable)Session["CurDtSalCats_CompMgmtPage"];
            dtSelCats.Rows.Clear();
         
            foreach (CompanyCategory compCat in colCompCat)
            {
                DataRow drSelcat = dtSelCats.NewRow();
                drSelcat["CategoryCode"] = compCat.Category.CategoryCode;
                drSelcat["CategoryName"] = compCat.Category.CategoryName;
                drSelcat["CategoryID"] = compCat.CategoryCode;
                dtSelCats.Rows.Add(drSelcat);
                Session["CalSelValues"] += compCat.CategoryCode + ",";
            }
            rptSelCats.DataSource = dtSelCats;
            rptSelCats.DataBind();
            Session["CurDtSalCats_CompMgmtPage"] = dtSelCats;

            

            //select Commercial compcats
            CompanyNewCommercialCategoryCollection colCompNewCat = comp.CompanyNewCommercialCategoryRecords(); //Commercial
            DataTable dtSelNewCats = (DataTable)Session["CurDtSalNewCats_CompMgmtPage"];
            dtSelNewCats.Rows.Clear();

            foreach (CompanyNewCommercialCategory compCat1 in colCompNewCat)
            {
                DataRow drSelcat = dtSelNewCats.NewRow();
                drSelcat["CategoryCode"] = compCat1.Category.CategoryCode;
                drSelcat["CategoryName"] = compCat1.Category.CategoryName;
                drSelcat["CategoryID"] = compCat1.NewCommercialCategoryCode;
                dtSelNewCats.Rows.Add(drSelcat);
                Session["CalNewSelValues"] += compCat1.NewCommercialCategoryCode +",";
            }
            rptSelnewCats.DataSource = dtSelNewCats;
            rptSelnewCats.DataBind();
            Session["CurDtSalNewCats_CompMgmtPage"] = dtSelNewCats;



            //select compModules
            CompanyModuleCollection colCompMod = comp.CompanyModuleRecords();

            foreach (CompanyModule compMod in colCompMod)
            {
                foreach (ListItem itm in lstModules.Items)
                {
                    if (itm.Value == compMod.ModuleID.ToString())
                        itm.Selected = true;

                }
            }


            //get the company Login user account
            DataTable dtUsr = VSiteUser.Query().SetTop("1").WHERE("CompanyCode", comp.CompanyCode).AND("RoleName", "company").ExecuteDataSet().Tables[0];

            if (dtUsr.Rows.Count > 0)
            {
                tbLoginName.Text = dtUsr.Rows[0]["UserName"].ToString();
                tbLoginName.Enabled = false; // username can't be changed
                tbPassword.Text = dtUsr.Rows[0]["Password"].ToString();
                tbEmail.Text = dtUsr.Rows[0]["Email"].ToString();
            }

            pnlForm.Focus();


        }

        protected void btnAdd_Click(object sender, ImageClickEventArgs e)
        {
            if (hdnFormMode.Value == "add" && hdnCurPkId.Value == "0")
            {

                string errMsg = "";

                Adex.Company comp = new Adex.Company();

                using (TransactionScope ts = new TransactionScope(TransactionScopeOption.Required, TimeSpan.FromMinutes(10)))
                {
                    using (SubSonic.SharedDbConnectionScope conn = new SubSonic.SharedDbConnectionScope(System.Configuration.ConfigurationManager.ConnectionStrings["DBAdex"].ToString()))
                    {


                        try
                        {

                            comp.CompanyName = this.tbCompanyName.Text;

                            comp.ValidFrom = Utility.ToDateTime(tbValidFrom.Text);
                            comp.ValidTo = Utility.ToDateTime(tbValidTo.Text);

                            comp.Credits = Utility.ToInt(tbCredits.Text);
                            comp.UnlimitedCredits = chkUnlimitedCredits.Checked;
                            comp.Active = chkAcitve.Checked;

                            comp.PricePerSecond = Utility.Tofloat(lstPriceKey.SelectedItem.Text);

                            if (lstNewsTemplate.SelectedValue != "")
                                comp.NewsTemplateID = Utility.ToInt(lstNewsTemplate.SelectedValue);
                            else
                                comp.NewsTemplateID = null;


                            comp.DateAdded = DateTime.Now;
                            comp.DateModified = DateTime.Now;

                            comp.Save();


                            //delete all exising CompCats
                            CompanyCategory.Delete("CompanyCode", comp.CompanyCode);

                            comp.UnlimitedCategories = chkUnlimitedCategories.Checked;
                            //save all selected categories

                            if (!comp.UnlimitedCategories)
                            {
                                DataTable dtSelCats = (DataTable)Session["CurDtSalCats_CompMgmtPage"];

                                foreach (DataRow drCat in dtSelCats.Rows)
                                {
                                    CompanyCategory compCat = new CompanyCategory();
                                    compCat.CompanyCode = comp.CompanyCode;
                                    //compCat.CategoryCode = Utility.ToInt(drCat["CategoryCode"]);
                                    compCat.CategoryCode = Utility.ToInt(drCat["CategoryID"]);
                                    compCat.DateAdded = DateTime.Now;
                                    compCat.DateModified = DateTime.Now;

                                    //colCompCat.Add(compCat);
                                    compCat.Save();

                                }//end foreach
                            }//end if


                            //delete all exising CompCats
                            CompanyNewCommercialCategory.Delete("CompanyCode", comp.CompanyCode);

                            comp.UnlimitedCommercialCategories = chkUnlimitedNewCategories.Checked;
                            //save all selected categories

                            if (!comp.UnlimitedCommercialCategories)
                            {
                                DataTable dtSelCats1 = (DataTable)Session["CurDtSalNewCats_CompMgmtPage"];

                                foreach (DataRow drCat in dtSelCats1.Rows)
                                {
                                    CompanyNewCommercialCategory compCat = new CompanyNewCommercialCategory();
                                    compCat.CompanyCode = comp.CompanyCode;
                                    //compCat.CategoryCode = Utility.ToInt(drCat["CategoryCode"]);
                                    compCat.NewCommercialCategoryCode = Utility.ToInt(drCat["CategoryID"]);
                                    compCat.DateAdded = DateTime.Now;
                                    compCat.DateModified = DateTime.Now;

                                    //colCompCat.Add(compCat);
                                    compCat.Save();

                                }//end foreach
                            }//end if
                            //Commercial End







                            //delete all exising CompModules
                            CompanyModule.Delete("CompanyCode", comp.CompanyCode);

                            //save all selected categories
                            foreach (ListItem itm in lstModules.Items)
                            {
                                if (itm.Selected)
                                {
                                    CompanyModule compMod = new CompanyModule();
                                    compMod.CompanyCode = comp.CompanyCode;
                                    compMod.ModuleID = Utility.ToInt(itm.Value);
                                    compMod.DateAdded = DateTime.Now;
                                    compMod.DateModified = DateTime.Now;

                                    compMod.Save();

                                }
                            }


                            comp.Logo = "noimage.jpg";

                            if (comp.CompanyCode > 0 && flLogo.FileName.Length > 0)
                            {
                                //upload logo
                                try
                                {
                                    comp.Logo = Utility.UploadImage(flLogo, "../images/companies/", comp.CompanyCode.ToString(), comp.Logo, true, 100, 100, 2, out errMsg);
                                }
                                catch (Exception ex)
                                {
                                    lblMsg.Text = lblMsg_top.Text = "Failed to upload Logo: " + ex.Message;
                                    //if image is not optional then uncomment the following line.
                                    throw new Exception("Failed to upload Logo: " + ex.Message);
                                }
                            }

                            //update again with pic changes
                            comp.Save();

                            lblMsg.Text = lblMsg_top.Text = "Client added successfully";

                            ts.Complete();

                        }//end first try
                        catch (Exception ex)
                        {
                            conn.Dispose();
                            ts.Dispose();
                            lblMsg.Text = lblMsg_top.Text = "Failed to save this Client: error--> " + ex.Message;
                            return;
                        }
                    }//end conn
                }//end ts


                //save user details after tran --> bcoz MSDTC do not work
                if (comp.CompanyCode > 0)
                {
                    try
                    {
                        int uid = AppUser.AddSiteUser(tbLoginName.Text.Trim(), tbPassword.Text.Trim(), "company", tbEmail.Text.Trim(), comp.CompanyCode, comp.Active, out errMsg);

                        if (uid <= 0)
                        {
                            // CompanyCategory.Delete("CompanyCode", comp.CompanyCode);
                            // CompanyModule.Delete("CompanyCode", comp.CompanyCode);
                            Company.Delete(comp.CompanyCode);
                            throw new Exception("Failed to save a new Website User account");
                        }
                    }
                    catch (Exception ex)
                    {
                        lblMsg.Text = lblMsg_top.Text = "Failed to save the company. " + ex.Message;
                        return;
                    }
                }
                //end setting user details


                hdnFormMode.Value = "add";
                hdnCurPkId.Value = "0";
                Utility.ClearForm(pnlForm);
                ClearSelectedCategorySelection();
                SetCrudButtons();

                pnlIno.Visible = true;
                pnlForm.Visible = false;
            }
        }

        protected void btnUpdate_Click(object sender, ImageClickEventArgs e)
        {
            if (hdnFormMode.Value == "edit" && hdnCurPkId.Value != "0")
            {


                string errMsg = "";

                Adex.Company comp = new Adex.Company(hdnCurPkId.Value);


                using (TransactionScope ts = new TransactionScope(TransactionScopeOption.Required, TimeSpan.FromMinutes(10)))
                {
                    using (SubSonic.SharedDbConnectionScope conn = new SubSonic.SharedDbConnectionScope(System.Configuration.ConfigurationManager.ConnectionStrings["DBAdex"].ToString()))
                    {

                        try
                        {
                            comp.CompanyName = this.tbCompanyName.Text;


                            comp.ValidFrom = Utility.ToDateTime(tbValidFrom.Text);
                            comp.ValidTo = Utility.ToDateTime(tbValidTo.Text);

                            comp.Credits = Utility.ToInt(tbCredits.Text);
                            comp.UnlimitedCredits = chkUnlimitedCredits.Checked;
                            comp.UnlimitedCategories = chkUnlimitedCategories.Checked;
                            comp.Active = chkAcitve.Checked;

                            comp.PricePerSecond = Utility.Tofloat(lstPriceKey.SelectedItem.Text);

                            if (lstNewsTemplate.SelectedValue != "")
                                comp.NewsTemplateID = Utility.ToInt(lstNewsTemplate.SelectedValue);
                            else
                                comp.NewsTemplateID = null;

                            comp.DateModified = DateTime.Now;

                            comp.Save();


                            //delete all exising CompCats
                            CompanyCategory.Delete("CompanyCode", comp.CompanyCode);

                            comp.UnlimitedCategories = chkUnlimitedCategories.Checked;
                            //save all selected categories

                            if (!comp.UnlimitedCategories)
                            {
                                DataTable dtSelCats = (DataTable)Session["CurDtSalCats_CompMgmtPage"];

                                foreach (DataRow drCat in dtSelCats.Rows)
                                {
                                    CompanyCategory compCat = new CompanyCategory();
                                    compCat.CompanyCode = comp.CompanyCode;
                                    //compCat.CategoryCode = Utility.ToInt(drCat["CategoryCode"]);
                                    compCat.CategoryCode = Utility.ToInt(drCat["CategoryID"]);
                                    compCat.DateAdded = DateTime.Now;
                                    compCat.DateModified = DateTime.Now;

                                    //colCompCat.Add(compCat);
                                    compCat.Save();

                                }//end foreach
                            }//end if

                            //Commercial Start
                            //delete all exising CompCats
                            CompanyNewCommercialCategory.Delete("CompanyCode", comp.CompanyCode);

                            comp.UnlimitedCommercialCategories = chkUnlimitedNewCategories.Checked;
                            //save all selected categories

                            if (!comp.UnlimitedCommercialCategories)
                            {
                                DataTable dtSelCats1 = (DataTable)Session["CurDtSalNewCats_CompMgmtPage"];

                                foreach (DataRow drCat in dtSelCats1.Rows)
                                {
                                    CompanyNewCommercialCategory compCat = new CompanyNewCommercialCategory();
                                    compCat.CompanyCode = comp.CompanyCode;
                                    //compCat.CategoryCode = Utility.ToInt(drCat["CategoryCode"]);
                                    compCat.NewCommercialCategoryCode = Utility.ToInt(drCat["CategoryID"]);
                                    compCat.DateAdded = DateTime.Now;
                                    compCat.DateModified = DateTime.Now;

                                    //colCompCat.Add(compCat);
                                    compCat.Save();

                                }//end foreach
                            }//end if
                            //Commercial End





                            //delete all exising CompModules
                            CompanyModule.Delete("CompanyCode", comp.CompanyCode);

                            //save all selected categories

                            foreach (ListItem itm in lstModules.Items)
                            {
                                if (itm.Selected)
                                {
                                    CompanyModule compMod = new CompanyModule();
                                    compMod.CompanyCode = comp.CompanyCode;
                                    compMod.ModuleID = Utility.ToInt(itm.Value);
                                    compMod.DateAdded = DateTime.Now;
                                    compMod.DateModified = DateTime.Now;

                                    compMod.Save();

                                }
                            }



                            if (comp.CompanyCode > 0 && flLogo.FileName.Length > 0)
                            {
                                //upload logo
                                try
                                {
                                    comp.Logo = Utility.UploadImage(flLogo, "../images/companies/", comp.CompanyCode.ToString(), comp.Logo, true, 100, 100, 2, out errMsg);
                                }
                                catch (Exception ex)
                                {
                                    lblMsg.Text = lblMsg_top.Text = "Failed to upload Logo: " + ex.Message;
                                    //if image is not optional then uncomment the following line.
                                    throw new Exception("Failed to upload Logo: " + ex.Message);
                                }
                            }

                            //update again with pic changes
                            comp.Save();




                            ts.Complete();
                            lblMsg.Text = lblMsg_top.Text = "Company updated successfully";

                        }//end first try
                        catch (Exception ex)
                        {
                            conn.Dispose();
                            ts.Dispose();
                            lblMsg.Text = lblMsg_top.Text = "Failed to update this Client: error--> " + ex.Message;
                            return;
                        }


                    }//end conn
                }//end ts


                //save user details -- after transaction becoz MSDTC doesn't work
                if (comp.CompanyCode > 0)
                {
                    try
                    {
                        int uid = 0;
                        //set User login details
                        DataTable dtUsr = VSiteUser.Query().SetTop("1").WHERE("CompanyCode", comp.CompanyCode).AND("RoleName", "company").ExecuteDataSet().Tables[0];

                        if (dtUsr.Rows.Count > 0)
                        {
                            uid = Utility.ToInt(dtUsr.Rows[0]["SiteUserID"]);
                            if (AppUser.UpdateUser(uid, tbLoginName.Text.Trim(), tbPassword.Text.Trim(), out errMsg) == false)
                                throw new Exception(errMsg);
                        }
                        //end setting the user login details
                        //activate the user associated with this company account.
                        if (!AppUser.SetSiteUserActivation(new SiteUser(uid), comp.Active))
                            throw new Exception("Errors saving SiteUser Activation settings");
                    }
                    catch (Exception ex)
                    {
                        lblMsg.Text = lblMsg_top.Text = "Failed to update company record. " + ex.Message;
                        return;
                    }

                }//end saving user

                hdnCurPkId.Value = "0";
                hdnFormMode.Value = "add";

                Utility.ClearForm(pnlForm);
                ClearSelectedCategorySelection();

                SetCrudButtons();

                pnlIno.Visible = true;
                pnlForm.Visible = false;

            }
        }

        protected void btnDelete_Click(object sender, ImageClickEventArgs e)
        {
            if (hdnCurPkId.Value.Length > 0 && hdnFormMode.Value == "edit")
            {
                try
                {

                    //delete company associated site user and it's login.
                    DataTable dtUsr = VSiteUser.Query().SetTop("1").WHERE("CompanyCode", hdnCurPkId).AND("RoleName", "company").ExecuteDataSet().Tables[0];

                    if (dtUsr.Rows.Count > 0)
                    {
                        SiteUser usr = new SiteUser(dtUsr.Rows[0]["SiteUserId"]);
                        AppUser.DeleteSiteUser(usr);
                        SiteUser.Delete(hdnCurPkId.Value);
                    }

                    Adex.Company.Delete(hdnCurPkId.Value);

                    lblMsg.Text = lblMsg_top.Text = "Selected Client deleted successfully";
                }
                catch (Exception ex)
                {
                    lblMsg.Text = lblMsg_top.Text = "Selected Client cannot be deleted. [" + ex.Message + "]";
                }

                hdnFormMode.Value = "add";
                hdnCurPkId.Value = "0";
                Utility.ClearForm(pnlForm);
                ClearSelectedCategorySelection();
                SetCrudButtons();

                pnlIno.Visible = true;
                pnlForm.Visible = false;
            }
        }

        protected void btnCancel_Click(object sender, ImageClickEventArgs e)
        {

            hdnCurPkId.Value = "0";
            hdnFormMode.Value = "add";
            Utility.ClearForm(pnlForm);
            ClearSelectedCategorySelection();

            SetCrudButtons();

            pnlIno.Visible = true;
            pnlForm.Visible = false;

        }

        private void SetCrudButtons()
        {
            btnCancel.Visible = btnDelete.Visible = btnUpdate.Visible = btnCancel_top.Visible = btnDelete_top.Visible = btnUpdate_top.Visible = hdnFormMode.Value == "edit";
            btnAdd.Visible = btnAdd_top.Visible = hdnFormMode.Value == "add";
        }

        protected void AddSelCats(Object sender, EventArgs e)
        {

            DataTable dtSelCats = (DataTable)Session["CurDtSalCats_CompMgmtPage"];

            foreach (Telerik.Web.UI.GridItem itm in radGridCats.SelectedItems)
            {
                string selCatCode = radGridCats.MasterTableView.DataKeyValues[itm.ItemIndex]["CategoryCode"].ToString();
                string selCatName = radGridCats.MasterTableView.DataKeyValues[itm.ItemIndex]["CategoryName"].ToString();
                string selCatID = radGridCats.MasterTableView.DataKeyValues[itm.ItemIndex]["CategoryID"].ToString();

                //if (itm.Selected==true)
                //if (dtSelCats.Select("CategoryCode = " + selCatCode).Length == 0)
                if (dtSelCats.Select("CategoryID = " + selCatID).Length == 0)
                {
                    DataRow drSelCat = dtSelCats.NewRow();
                    drSelCat["CategoryCode"] = selCatCode;
                    drSelCat["CategoryName"] = selCatName;
                    drSelCat["CategoryID"] = selCatID;
                    dtSelCats.Rows.Add(drSelCat);

                }
            }//end loop

            rptSelCats.DataSource = dtSelCats;
            rptSelCats.DataBind();

            Session["CurDtSalCats_CompMgmtPage"] = dtSelCats;
        }


        protected void AddNewSelCats(Object sender, EventArgs e) //Commercial
        {

            DataTable dtSelCats = (DataTable)Session["CurDtSalNewCats_CompMgmtPage"];

            foreach (Telerik.Web.UI.GridItem itm in radGridNewCats.SelectedItems)
            {
                string selCatCode = radGridNewCats.MasterTableView.DataKeyValues[itm.ItemIndex]["CategoryCode"].ToString();
                string selCatName = radGridNewCats.MasterTableView.DataKeyValues[itm.ItemIndex]["CategoryName"].ToString();
                string selCatID = radGridNewCats.MasterTableView.DataKeyValues[itm.ItemIndex]["CategoryID"].ToString();
                //if (dtSelCats.Select("CategoryCode = " + selCatCode).Length == 0)
                if (dtSelCats.Select("CategoryID = " + selCatID).Length == 0)
                {
                    DataRow drSelCat = dtSelCats.NewRow();
                    drSelCat["CategoryCode"] = selCatCode;
                    drSelCat["CategoryName"] = selCatName;
                    drSelCat["CategoryID"] = selCatID;
                    dtSelCats.Rows.Add(drSelCat);

                }
            }//end loop

            rptSelnewCats.DataSource = dtSelCats;
            rptSelnewCats.DataBind();

            Session["CurDtSalNewCats_CompMgmtPage"] = dtSelCats;
        }


        
         protected void unlimitedCredits_CheckChanged(Object sender, EventArgs e)
        {
            CheckBox chk = (CheckBox)sender;
            tbCredits.Enabled = !chk.Checked;
            tbCredits.Text = chk.Checked ? "9999999" : "0";
        }

        protected void chkUnlimitedCategories_CheckChanged(Object sender, EventArgs e)
        {
            CheckBox chk = (CheckBox)sender;
            radGridCats.Visible = !chk.Checked;

            if (chk.Checked)
                ClearSelectedCategorySelection();
        }
         private void ClearSelectedCategorySelection()
        {
            radGridCats.SelectedIndexes.Clear();
            DataTable dtSelCats = (DataTable)Session["CurDtSalCats_CompMgmtPage"];
            dtSelCats.Clear();
            rptSelCats.DataSource = dtSelCats;
            rptSelCats.DataBind();
            Session["CurDtSalCats_CompMgmtPage"] = dtSelCats;
        }

        //Commercial
        protected void lnkAddNew_Click(object sender, EventArgs e)
        {
            hdnCurPkId.Value = "0";
            hdnFormMode.Value = "add";
            pnlIno.Visible = false;
            pnlForm.Visible = true;
        }

        #region[Commercial]
        private void ClearSelectedNewCategorySelection() //Commercial
        {
            radGridNewCats.SelectedIndexes.Clear();
            DataTable dtSelCats = (DataTable)Session["CurDtSalNewCats_CompMgmtPage"];
            dtSelCats.Clear();
            rptSelnewCats.DataSource = dtSelCats;
            rptSelnewCats.DataBind();
            Session["CurDtSalNewCats_CompMgmtPage"] = dtSelCats;
        }
        protected void chkUnlimitedNewCategories_CheckChanged(Object sender, EventArgs e) //Commercial
        {
            CheckBox chk = (CheckBox)sender;
            radGridNewCats.Visible = !chk.Checked;

            if (chk.Checked)
                ClearSelectedNewCategorySelection();
        }

        protected void DelSelCatCode(Object sender, EventArgs e)
        {
            String ValueinSessionCat = Session["CalSelValues"].ToString();
            string id = ((LinkButton)sender).CommandArgument;

            DataTable dtSelCats = (DataTable)Session["CurDtSalCats_CompMgmtPage"];

            //DataRow[] drs = dtSelCats.Select("CategoryCode=" + id);
            DataRow[] drs = dtSelCats.Select("CategoryID=" + id);
            if (drs.Length > 0)
            {
                dtSelCats.Rows.Remove(drs[0]);

                foreach (Telerik.Web.UI.GridItem itm in radGridCats.SelectedItems)
                {
                    if (radGridCats.MasterTableView.DataKeyValues[itm.ItemIndex]["CategoryID"].ToString() == id)
                    {
                        itm.Selected = false;
                    }

                }//end loop

                ValueinSessionCat = ValueinSessionCat.Replace(id + ",", "");
            }

            rptSelCats.DataSource = dtSelCats;
            rptSelCats.DataBind();

            Session["CurDtSalCats_CompMgmtPage"] = dtSelCats;
            Session["CalSelValues"] = ValueinSessionCat;
        }


        protected void DelNewSelCatCode(Object sender, EventArgs e) //Commercial
        {
            String ValueinSession = Session["CalNewSelValues"].ToString();
            string id = ((LinkButton)sender).CommandArgument;

            DataTable dtSelCats = (DataTable)Session["CurDtSalNewCats_CompMgmtPage"];

            //DataRow[] drs = dtSelCats.Select("CategoryCode=" + id);
            DataRow[] drs = dtSelCats.Select("CategoryID=" + id);
            if (drs.Length > 0)
            {
                dtSelCats.Rows.Remove(drs[0]);

                foreach (Telerik.Web.UI.GridItem itm in radGridNewCats.SelectedItems)
                {
                    if (radGridNewCats.MasterTableView.DataKeyValues[itm.ItemIndex]["CategoryID"].ToString() == id)
                    {
                        itm.Selected = false;
                    }

                }//end loop

                ValueinSession = ValueinSession.Replace(id+",","");
            }

            rptSelnewCats.DataSource = dtSelCats;
            rptSelnewCats.DataBind();
            Session["CurDtSalNewCats_CompMgmtPage"] = dtSelCats;
            Session["CalNewSelValues"] = ValueinSession;
            
            
        }

       

      
        #endregion

    }
}